import { ref,computed } from "vue";
import { useIntersectionObserver, useIntervalFn } from "@vueuse/core";
import dayjs from 'dayjs'
/* 懒加载 */
export function useObserver(apiFn) {
  const target = ref(null);
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      console.log(isIntersecting, 5555);
      if (isIntersecting) {
        stop(); //  终止监听
        // apiFn && apiFn()
        if (apiFn) {
          apiFn();
        }
      }
    }
  );

  return target;
}

export const useCountDown = (startCount) => {
  const countTime = ref(0);
  // pause 暂停定时器
  const { pause, resume } = useIntervalFn(() => {
    if (countTime.value <= 0) {
      pause();
      return;
    }
    // 倒计时，就是每隔一秒减一
    countTime.value--;
  }, 1000);
  // 重新开始（倒计时的数字）
  const countTimeText = computed(() => {
    return dayjs.unix(countTime.value).format('mm分ss秒')
  })
  function start(countdown) {
    countTime.value = countdown || startCount;
    resume();
  }
  return {
    countTime,
    start,
    pause,
    resume,
    countTimeText
  };
};
